import React, { useState, useEffect } from 'react';
import { Table, Button, Space, Tooltip, message } from 'antd';
import { UserOutlined } from '@ant-design/icons';
import { MSGraphClientFactory } from '@microsoft/sp-http';

const MailHanding = (props) => {
  console.log('MailHanding props:', props);
  const { context } = props;
  const [timeRange, setTimeRange] = useState('past-week');
  const [emailData, setEmailData] = useState([]);
  const [loading, setLoading] = useState(false);
  const [emailStats, setEmailStats] = useState({
    totalReplied: 0,
    repliedToday: 0,
    needsReview: 0,
    importantLeader: 0,
    needsDownload: 0,
    fromExternal: 0,
    markedUrgent: 0
  });
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);

  // 获取邮件数据
  const fetchEmailData = async () => {
    setLoading(true);
    setEmailData([]);
    setEmailStats({
        totalReplied: 0, repliedToday: 0, needsReview: 0, importantLeader: 0,
        needsDownload: 0, fromExternal: 0, markedUrgent: 0
    });

    try {
      if (!context) {
        console.error('SharePoint context未定义');
        message.error('无法获取SharePoint context');
        return;
      }

      // 根据时间范围设置筛选条件
      let dateFilter = '';
      const now = new Date();
      const todayStart = new Date(now);
      todayStart.setHours(0, 0, 0, 0); // 今天的开始时间

      switch(timeRange) {
           case 'past-week':
                const pastWeekStart = new Date(todayStart);
                pastWeekStart.setDate(todayStart.getDate() - 7);
                dateFilter = `receivedDateTime ge ${pastWeekStart.toISOString()} and receivedDateTime le ${now.toISOString()}`;
                break;
           case 'next-two-weeks': // 过去14天的邮件
                 const pastTwoWeeksStart = new Date(todayStart);
                 pastTwoWeeksStart.setDate(todayStart.getDate() - 14);
                 dateFilter = `receivedDateTime ge ${pastTwoWeeksStart.toISOString()} and receivedDateTime le ${now.toISOString()}`;
                 break;
           case 'next-four-weeks': // 过去28天的邮件
                 const pastFourWeeksStart = new Date(todayStart);
                 pastFourWeeksStart.setDate(todayStart.getDate() - 28);
                 dateFilter = `receivedDateTime ge ${pastFourWeeksStart.toISOString()} and receivedDateTime le ${now.toISOString()}`;
                 break;
           default: // 默认过去一周
                 const defaultPastWeekStart = new Date(todayStart);
                 defaultPastWeekStart.setDate(todayStart.getDate() - 7);
                 dateFilter = `receivedDateTime ge ${defaultPastWeekStart.toISOString()} and receivedDateTime le ${now.toISOString()}`;
                 break;
       }

      // 使用 MSGraphClientFactory 获取 Graph 客户端
      const graphClient = await context.msGraphClientFactory.getClient();

      // 调用 Microsoft Graph API 获取邮件
      const response = await graphClient
        .api(`/me/messages`)
        .filter(dateFilter) // 应用日期筛选
        .top(100) // 根据需要调整数量
        .orderby('receivedDateTime desc')
        .get();

      console.log('获取的邮件数据:', response);

      // 处理邮件数据
      const formattedData = response.value.map(email => {
        // 处理回复状态
        const processedStatus = {
          text: email.isRead ? '已处理' : '待处理',
          type: email.isRead ? 'processed' : 'pending-process'
        };

        // 处理回复时间
        const processedTime = email.isRead ? new Date(email.lastModifiedDateTime).toLocaleString('zh-CN', {
          month: 'numeric',
          day: 'numeric',
          weekday: 'short',
          hour: '2-digit',
          minute: '2-digit'
        }) : '-';

        return {
          key: email.id,
          id: email.id,
          sender: email.from?.emailAddress?.name || '未知发件人',
          sendTime: new Date(email.receivedDateTime).toLocaleString('zh-CN', {
            month: 'numeric',
            day: 'numeric',
            weekday: 'short',
            hour: '2-digit',
            minute: '2-digit'
          }),
          subject: email.subject || '(无主题)',
          priority: {
            text: email.importance === 'high' ? '高' : email.importance === 'low' ? '低' : '普通',
            type: email.importance === 'high' ? 'high' : email.importance === 'low' ? 'low' : 'normal'
          },
          replyStatus: processedStatus,
          replyTime: processedTime,
          emailType: email.hasAttachments ? '需要下载' : '普通邮件'
        };
      });

      setEmailData(formattedData);

      // 计算邮件统计数据
      const calculatedStats = {
        // 计算已处理总数（使用isRead作为代理）
        totalReplied: formattedData.filter(email => email.replyStatus.type === 'processed').length,
        // 计算今天处理的（使用isRead和receivedDateTime作为代理）
        repliedToday: formattedData.filter(email => {
          const processed = email.replyStatus.type === 'processed';
          if (!processed) return false;
          const processDate = new Date(email.replyTime !== '-' ? email.replyTime : email.sendTime);
          const today = new Date();
          return processDate.getDate() === today.getDate() &&
                 processDate.getMonth() === today.getMonth() &&
                 processDate.getFullYear() === today.getFullYear();
        }).length,
        needsReview: formattedData.filter(email => email.replyStatus.type === 'pending-process').length,
        importantLeader: 0, // 需要根据发件人邮箱模式或组来确定
        needsDownload: formattedData.filter(email => email.emailType === '需要下载').length,
        fromExternal: formattedData.filter(email => {
            // 基本检查外部邮件（需要公司域名）
            const senderEmail = email.from?.emailAddress?.address || '';
            return senderEmail && !senderEmail.endsWith('@yourcompany.com'); // *** 替换为实际域名 ***
        }).length,
        markedUrgent: formattedData.filter(email => email.priority.type === 'high').length
      };

      setEmailStats(calculatedStats);

    } catch (error) {
      console.error('获取邮件数据时出错:', error);
      message.error('获取邮件数据失败，请稍后重试');
      setEmailData([]);
      setEmailStats({
            totalReplied: 0, repliedToday: 0, needsReview: 0, importantLeader: 0,
            needsDownload: 0, fromExternal: 0, markedUrgent: 0
        });
    } finally {
      setLoading(false);
    }
  };

  // 当时间范围或context变化时获取邮件数据
  useEffect(() => {
    if (context) {
      fetchEmailData();
    }
  }, [timeRange, context]);

  // Handle table pagination, sorting, and filtering changes
  const handleTableChange = (pagination, filters, sorter) => {
    setCurrentPage(pagination.current);
    setPageSize(pagination.pageSize);
    // Note: Sorting and filtering logic can be added here if needed in the future
  };

  // 获取邮件数量
  const getEmailCount = () => {
    return emailData.length;
  };

  // 表格列定义
  const columns = [
    { title: '序号', dataIndex: 'id', key: 'id', width: '5%', render: (text, record, index) => index + 1 },
    { title: '发件人姓名', dataIndex: 'sender', key: 'sender', width: '10%', },
    { title: '发送时间', dataIndex: 'sendTime', key: 'sendTime', width: '12%', },
    { title: '主题', dataIndex: 'subject', key: 'subject', width: '22%', ellipsis: { showTitle: false, }, render: subject => (<Tooltip placement="topLeft" title={subject}><span>{subject}</span></Tooltip>), },
    { title: '优先级', dataIndex: 'priority', key: 'priority', width: '8%', render: (priority) => (<span className={`priority-badge ${priority.type === 'high' ? 'priority-high' : 'priority-low'}`}>{priority.text}</span>), },
    { title: '处理状态', dataIndex: 'replyStatus', key: 'replyStatus', width: '10%', render: (status) => (<span className={`reply-status ${status.type === 'processed' ? 'status-processed' : 'status-pending-process'}`}>{status.text}</span>), },
    { title: '处理时间', dataIndex: 'replyTime', key: 'replyTime', width: '12%', },
    { title: '邮件类型', dataIndex: 'emailType', key: 'emailType', width: '10%', },
  ];

  // 设置行样式
  const getRowClassName = (record, index) => {
    return index % 2 === 1 ? 'light-blue-row' : '';
  };

  return (
    <div className="email-container">
      <style jsx="true">
        {`
          .email-container { padding: 20px; }
          .light-blue-row { background-color: #f0f8ff; }
          .ant-table-tbody > tr.light-blue-row:hover > td { background-color: #e6f4ff; }
          .page-title { margin: 0 0 10px 0; }
          .email-info { margin: 10px 0; }
          .description { color: #666; margin: 5px 0 15px 0; }
          .emoji { font-size: 16px; margin-right: 5px; }
          .button-container { display: flex; justify-content: flex-end; margin-bottom: 15px; }
          .email-count { color: #1890ff; font-size: 18px; font-weight: bold; }
          .stat-number { color: #1890ff; font-weight: bold; }
          .header-section { margin-bottom: 20px; }
          .table-container { background-color: #fff; width: 100%; }
          .hover-content { cursor: pointer; }
          .priority-badge { cursor: pointer; }
          .reply-status { cursor: pointer; }
          .priority-high { color: #faad14; }
          .priority-low { color: #1890ff; }
          .status-processed { color: #52c41a; }
          .status-pending-process { color: #f5222d; }
          .ant-table-container { width: 100%; }
          .ant-table { width: 100%; }
          .ant-table-cell { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
          .ant-table-wrapper { width: 100%; }
        `}
      </style>

      <style global jsx>
        {`
          .ant-tooltip-inner { background-color: white; color: black; border: 1px solid #e8e8e8; }
          .ant-tooltip-arrow-content { background-color: white; border: 1px solid #e8e8e8; }
        `}
      </style>

      <div className="header-section">
        <h2 className="page-title">邮件处理</h2>
        <p className="email-info">
          {timeRange === 'past-week' ? '过去一周' : timeRange === 'next-two-weeks' ? '过去两周' : '过去四周'}您一共收到
          <span className="email-count"> {getEmailCount()} </span> 封邮件
        </p>
        <p className="description">
          请及时处理重要邮件！<span className="emoji">📧</span>
        </p>
        
        <div className="button-container">
          <Space>
            <Button 
              type={timeRange === 'past-week' ? 'primary' : 'default'} 
              ghost={timeRange === 'past-week'}
              onClick={() => setTimeRange('past-week')}
            >
              过去一周
            </Button>
            <Button 
              type={timeRange === 'next-two-weeks' ? 'primary' : 'default'} 
              ghost={timeRange === 'next-two-weeks'}
              onClick={() => setTimeRange('next-two-weeks')}
            >
              过去两周
            </Button>
            <Button 
              type={timeRange === 'next-four-weeks' ? 'primary' : 'default'} 
              ghost={timeRange === 'next-four-weeks'}
              onClick={() => setTimeRange('next-four-weeks')}
            >
              过去四周
            </Button>
          </Space>
        </div>
      </div>

      <Table
        dataSource={emailData.slice((currentPage - 1) * pageSize, currentPage * pageSize)}
        columns={columns}
        loading={loading}
        rowClassName={getRowClassName}
        className="table-container"
        pagination={{
          current: currentPage,
          pageSize: pageSize,
          total: emailData.length,
          showSizeChanger: true,
          showQuickJumper: true,
          position: ['bottomRight'],
        }}
        onChange={handleTableChange}
      />
    </div>
  );
};

export default MailHanding;